package com.supermap.desktop.utilities;

import org.junit.Ignore;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.*;

/**
 * Created by caolp
 */
@Ignore
public class CommonMethod {

	//获取工作空间、数据源路径
	public static String getPath(String relativePath) {
		String classPath = CommonMethod.class.getProtectionDomain().getCodeSource().getLocation().getPath();
		String path = classPath + relativePath;
		//去掉路径开头多余字符
		path = path.substring(1, path.length());
		return path;
	}

	//将字符串转换为文档比较
	public static Boolean compareXMLString(String xmlString1,
	                                       String xmlString2) throws SAXException, IOException,
			ParserConfigurationException {
		Boolean result = true;
		DocumentBuilder db = DocumentBuilderFactory.newInstance()
				.newDocumentBuilder();
		Document doc1 = db.parse(new InputSource(new StringReader(xmlString1)));
		Document doc2 = db.parse(new InputSource(new StringReader(xmlString2)));
		result = compareDocumentNodes(doc1, doc2);
		return result;
	}

	//比较文档节点，可以直接传入document参数
	public static boolean compareDocumentNodes(Node node1, Node node2) {
		String nodeName = node1.getNodeName();
		if (nodeName.startsWith("#") && node1.getParentNode() != null) {
			nodeName = node1.getParentNode().getNodeName() + node1.getNodeName();
		}
		int len1 = node1.getChildNodes().getLength();
		int len2 = node2.getChildNodes().getLength();
		if (len1 > 0) {
			if (len1 != len2) {
				System.out.println(nodeName + "  子节点数应为" + len1 + "，实际为" + len2);
				return false;
			} else {
				for (int i = 0; i < len1; i++) {
					Node n1 = node1.getChildNodes().item(i);
					Node n2 = node2.getChildNodes().item(i);
					compareDocumentNodes(n1, n2);
				}
			}
		} else {
			if (!node1.isEqualNode(node2)) {
				System.out.println(nodeName + " value应该为：" + node1.getNodeValue() + " ,实际为：" + node2.getNodeValue());
				System.out.println(nodeName + " text应该为：" + node1.getTextContent() + ",实际为：" + node2.getTextContent());
				return false;
			}
		}
		return true;
	}

	/**
	 * 读取文件到字符串
	 */
	public static String fileToString(File file) throws IOException {
		String lines = "";
		BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
		String line;
		while ((line = br.readLine()) != null) {
			lines += line;
		}
		return lines;
	}
}
